<template>
  <view>
    <up-popup mode="bottom" :customStyle="{ width: '100vw', height: 'auto', padding: '20rpx 0' }"
      v-model:show="MoreOptionsPop">
      <view class="more-options-container">
        <!-- 功能选项 -->
        <view class="options-row">

          <view class="option-item" style="color: #000;" v-if="formData.submitpower" @click="ResubmitClick(formData)">
            <uni-icons type="refreshempty" size="32" color="#000"></uni-icons>
            <text class="option-text">再次提交</text>
          </view>

          <view class="option-item" style="color: #1890ff;" v-if="formData.checkpower" @click="passon">
            <up-icon name="share-square" size="32" color="#1890ff"></up-icon>
            <text class="option-text">转交</text>
          </view>

          <view class="option-item" @click="handleOptionClick('share')">
            <up-icon name="share" size="32" color="#17181c"></up-icon>
            <text class="option-text">分享</text>
          </view>

          <view class="option-item" @click="handleOptionClick('download')">
            <up-icon name="download" size="32" color="#17181c"></up-icon>
            <text class="option-text">下载</text>
          </view>

          <view class="option-item" @click="handleOptionClick('print')">
            <image :src="dayinimg" style="width: 25px; height: 25px;padding-top: 12rpx;"></image>
            <text class="option-text">打印</text>
          </view>
        </view>


        <!-- 取消按钮 -->
        <view class="cancel-btn" @click="closeMoreOptions">取消</view>
      </view>
    </up-popup>

    <!-- 弹窗组件 -->
    <modalindex ref="modalindex" :modalTitle="modalTitle" :modalPlaceholder="modalPlaceholder"
      :Doyouwanttoinput="Doyouwanttoinput" @handleModalConfirm="handleModalConfirm"></modalindex>

    <!-- 评论弹窗 -->
    <commentPopup ref="commentPopup" :formData="formData" :nextCloud="nextCloud" :orderId="orderId"
      :userStore="userStore" :CommentName="CommentName" :commentText="commentText" :passonType="passonType">
    </commentPopup>
  </view>
</template>

<script>
import apply from "@/apis/cloud/apply.js"
import dayinimg from '@/static/apply/dayin.png'
import modalindex from '@/components/Operationboxpublic/modalindex.vue'
import { getdownloadFileH5 } from '@/utils/publicmethod.js'
import commentPopup from './commentPopup.vue'
export default {
  name: 'moreOptionsPopup',
  props: {
    formData: {
      type: Object,
      default: {}
    },
    userStore: {
      type: Object,
      default: {}
    },
    nextCloud: {
      type: String,
      default: ''
    },
    orderId: {
      type: String,
      default: ''
    },

  },
  components: {
    modalindex,
    commentPopup
  },
  data () {
    return {
      dayinimg,
      MoreOptionsPop: false,
      modalTitle: '',
      modalPlaceholder: '',
      Doyouwanttoinput: '',
      passonList: [],
      CommentName: '',
      passonType: '',
      isCommentModalVisible: false,
      commentText: '',
      customInputMentions: [],
      uploadimgList: [],
      uploadFilesList: [],
    }
  },
  created () {
    uni.$on('passon', (data) => {
      this.Transfertheevent(data)
    })
  },
  methods: {
    Transfertheevent (e) {
      this.passonList = e
      if (this.passonList && this.passonList[0].id) {
        let data = {
          CommentName: `转交给${this.passonList[0].name}`,
          passonType: 2,
          commentText: '',
          customInputMentions: [],
          uploadimgList: [],
          uploadFilesList: [],
          passonList: this.passonList
        }

        setTimeout(() => {
          this.$refs.commentPopup.commentPopupClick(data)
        }, 100);
      } else {
        setTimeout(() => {
          uni.showToast({
            title: '未选择转交人员',
            icon: 'none',
          });
        }, 50);
      }
    },
    // 打开弹窗
    openMoreOptions () {
      this.MoreOptionsPop = true
    },
    // 弹窗组件方法
    handleModalConfirm () {

    },
    // 重新提交
    ResubmitClick (value) {
      uni.navigateTo({
        url: `/pages/apply/form/index?id=${value.formId}&form_id=${this.orderId}`
      });
    },
    // 转交
    passon () {
      this.closeMoreOptions()
      setTimeout(() => {
        uni.navigateTo({
          url: '/components/OrgPicker/index?overlay=false&entry=component&VisibleandHidden=true&title=转交人员选择&type=user&multiple=false&source=passon'
        });
      }, 100);

    },
    // 处理选项点击事件
    handleOptionClick (option) {
      switch (option) {
        case 'share':
          uni.navigateTo({
            url: `/pages/apply/components/shareApprovalForm?id=${this.orderId}`,
          })
          break;
        case 'download':
          this.downloadClick()
          break;
        case 'print':
          this.printClick()
          break;
        default:
          break;
      }
      this.MoreOptionsPop = false
    },
    // 关闭
    closeMoreOptions () {
      this.MoreOptionsPop = false
    },
    // 下载文件
    async downloadClick () {
      try {
        uni.showLoading({ title: '正在下载', mask: true });

        const result = await apply.ApplydownloadPdf({ id: this.orderId });

        if (result.status !== 1 || !result.data.pdf_url) {
          uni.showToast({
            title: result.msg || '下载失败',
            icon: 'error'
          });
          return
        }

        const fileUrl = result.data.pdf_url;
        const fileName = result.data.filename
        const savePath = "file://storage/emulated/0/绿港云/" + fileName;
        // #ifdef APP-PLUS
        // 创建下载任务
        const dtask = plus.downloader.createDownload(fileUrl, {
          filename: savePath
        }, (downloadedFile, status) => {
          uni.hideLoading();
          if (status === 200) {
            // 下载成功
            uni.showToast({
              title: '已保存到文件夹：/绿港云/' + fileName,
              icon: 'none',
              duration: 3000,
            });

            // 打开文件
            setTimeout(() => {
              plus.runtime.openFile(downloadedFile.filename);
            }, 1500);
          } else {
            // 下载失败
            plus.downloader.clear(); // 清除任务
            uni.showToast({
              title: '下载失败，请稍后重试',
              icon: 'error'
            });
          }
        });

        dtask.start(); // 开始下载
        // #endif


        // #ifdef H5
        this.downloadFileH5(fileUrl, fileName);
        // #endif

        uni.hideLoading();
      } catch (e) {
        uni.hideLoading();
        uni.showToast({
          title: e.message || '下载失败',
          icon: 'error',
          duration: 2000
        });
      }
    },
    // 浏览器 下载pdf
    async downloadFileH5 (fileUrl, name) {
      getdownloadFileH5(fileUrl, name, this.nextCloud.xtoken, this.userStore.user.worker_id)
    },
    // 打印
    async printClick () {
      try {
        const result = await apply.ApplygeneratePdf({ id: this.orderId });

        if (result.status !== 1) {
          uni.showToast({
            title: result.msg || '下载失败',
            icon: 'error'
          });
          return
        }

        let pdfUrl = result.data.download_url

        this.handlePrint(pdfUrl);

      } catch (e) {

      }
    },
    handlePrint (pdfUrl) {
      const platform = uni.getSystemInfoSync().platform;

      // #ifdef H5
      this.downloadFileH5(pdfUrl, `${this.formData.title}.pdf`)
      // #endif

      // APP 平台
      // #ifdef APP-PLUS
      this.downloadAndOpenPdf(pdfUrl);
      // #endif
    },
    downloadAndOpenPdf (pdfUrl) {
      const downloadTask = uni.downloadFile({
        url: pdfUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            const filePath = res.tempFilePath;
            uni.openDocument({
              filePath: filePath,
              fileType: 'pdf',
              success: () => {
                console.log('打开文档成功');
              },
              fail: (err) => {
                uni.showToast({ title: '无法打开文件', icon: 'error' });
                console.error(err);
              }
            });
          } else {
            uni.showToast({ title: '下载失败', icon: 'error' });
          }
        },
        fail: (err) => {
          console.error(err);
          uni.showToast({ title: '下载失败', icon: 'error' });
        }
      });
    },
    destroyClick () {
      uni.$off('passon');
    },
  }
}
</script>


<style lang="scss" scoped>
@import "../applyOrderDetail.scss";
</style>